﻿/*
创建人：Yuxj
日期：2023-03-29
描述：手动排班js
*/
var page = {
    pagetotal: 0,
    pageSize: 15,
    pageNumber: 1,    
    rootPath: getRootPath(), //网站根路径
    ajaxUrl: getRootPath() + "/Ashx/ApsHandler/ApsEmployeeArrangeHandler.ashx",
    commonUrl: getRootPath() + "/Ashx/CommonHandler.ashx",   
    cmbWorkShiftValue:null,//通过弹窗获取指定的班次id(暂没有用)
    shiftTable:null,//Grid加载动态列时赋值   
    clickField:null,

    //初始化页面
    init: function () {
        page.bind();
        page.InitgdEmpWkShiftSumInfo([]);
        NewcustomizedEasyuiPagination('pp'); //定制化分页
        $('#pp').find('.pageSize').val(page.pageSize); //初始化行数
        page.apsUploader();
        page.addEditCell();
    },
    InitgdEmpWkShiftSumInfo:function(columns){
        //主查询结果加载
        $("#gdEmpWkShiftSumInfo").datagrid({
            rownumbers: true,   
            frozenColumns: [[
                 { field: 'FULLNAME', title: '人员姓名', width: 120,align:'center' },
		         { field: 'EMPLOYEENAME', title: '员工号', width: 150 ,align:'center'}
	           ]],
            columns:[columns],
            onClickCell: function (index, field) {
                //编辑单元格
                if (page.endEditing('gdEmpWkShiftSumInfo')) {
                    $('#gdEmpWkShiftSumInfo').datagrid('editCell', { index: index, field: field });
                    page.editIndex = index;
                    page.clickField=field;//动态列，提前获取列名后 为取值使用
                }               
            },
            onBeforeEdit:function(rowIndex, rowData){               
            },
            onAfterEdit:function(index,row,change){  
                    if((page.clickField!="FULLNAME")&&(page.clickField!="EMPLOYEENAME") &&(row[page.clickField]!=null)&&(row[page.clickField]!=""))
                    {
                        page.saveWorkShift(row[page.clickField],row["EMPLOYEENAME"],page.clickField);   
                        page.searchApsEmployeeWorkSum();
                        page.searchApsEmployeeWorkDetail();                    
                    }                    
                }
        });
    },
    addEditCell: function () //给easyuigrid新增editcell方法
    {
        $.extend($.fn.datagrid.methods, {
            editCell: function (jq, param) {
                return jq.each(function () {
                    var opts = $(this).datagrid('options');
                    var fields = $(this).datagrid('getColumnFields', true).concat($(this).datagrid('getColumnFields'));
                    for (var i = 0; i < fields.length; i++) {
                        var col = $(this).datagrid('getColumnOption', fields[i]);
                        col.editor1 = col.editor;
                        if (fields[i] != param.field) {
                            col.editor = null;
                        }
                    }
                    $(this).datagrid('beginEdit', param.index);
                    for (var i = 0; i < fields.length; i++) {
                        var col = $(this).datagrid('getColumnOption', fields[i]);
                        col.editor = col.editor1;
                    }
                });
            }
        });
    },
    endEditing: function (gridId) {
            if (page.editIndex == undefined) { return true }
            if ($('#' + gridId).datagrid('validateRow', page.editIndex)) {
                $('#' + gridId).datagrid('endEdit', page.editIndex);
                page.editIndex = undefined; 
                return true;
            } else { 
                return false;
            }
        },
    //页面事件绑定
    bind: function () {
        page.LoadWorkShift();
        $('#dg').hide();
        $('#txtStartDate').datebox('setValue', dayjs().startOf('month').format('YYYY-MM-DD'));
        $('#txtEndDate').datebox('setValue', dayjs().endOf('month').format('YYYY-MM-DD'));

        //人员日班次详情
         $("#gdEmpWkShiftDetailInfo").datagrid({
            onLoadSuccess: function (data) {
                $('#pp').pagination('refresh', {	// 改变选项，并刷新分页栏信息
                    total: page.pagetotal,
                    pageSize: page.pageSize,
                    pageNumber: page.pageNumber
                });
                NewcustomizedEasyuiPagination('pp'); //定制化分页
            },
            columns: [[
                 { field: 'FULLNAME', title: '人员姓名', width: 120,align:'center' },
		         { field: 'EMPLOYEENAME', title: '员工号', width: 150 ,align:'center'},
                 { field: 'WORKSHIFTNAME', title: '班次', width: 150 ,align:'center'
                   
                 },
		         { field: 'WORKDATE', title: '日期', width: 120 ,align:'center'},
                 { field: 'STARTDATE', title: '开始时间', width: 120 ,align:'center'},
                 { field: 'ENDDATE', title: '结束时间', width: 120 ,align:'center'},
                 { field: 'MINS', title: '持续时长', width: 120 ,align:'center'}              

	           ]]
        });
        
        //分页事件
        $('#pp').pagination({
            onSelectPage: function (pageNumber, pageSize) {
                NewcustomizedEasyuiPagination('pp'); //定制化分页
                page.pageSize = pageSize; page.pageNumber = pageNumber;
                page.searchApsEmployeeWorkDetail();
            }
        });

        //排产结果导入错误列表
         $("#ErrorTable").datagrid({
          columns:[[             
              { field: 'Error', title: '出错原因',width:'400px' }
          ]]
         });
        //绑定分页go按钮
        $('#pageGo').on("click", function () {
            var pageNumber = $(this).parents('tr').find('.pagination-num').val();
            page.pageNumber = pageNumber;
            page.pageSize=$('#pp').find('.pageSize').val() == "" ? page.pageSize : Number($('#pp').find('.pageSize').val());
            page.searchApsEmployeeWorkDetail();
        });
        //加载分厂
        page.LoadFactory();
        //查询按钮
        $('#btnSearch').on("click", function () { 
                page.reset(false, true, true);
                page.pageNumber = 1;               
                page.searchData();    
        });

        //弹窗确定按钮
        $('#btnSubmit').on("click", function () {        
             cmbWorkShiftValue=$('#cmbWorkShift').combobox('getValue');
             $('#dg').dialog('close');             
             
        });

         //弹窗确定按钮
        $('#btnCancel').on("click", function () {                    
             $('#dg').dialog('close');                              
        });
        
        //清除按钮
        $('#btnReset').on("click", function () {
            page.reset(true, true, true);
            page.pageNumber = 1; page.pagetotal = 0
            $('#pp').pagination('refresh', {
                total: page.pagetotal,
                pageSize: page.pageSize,
                pageNumber: page.pageNumber
            });
        });

         $('#btnEmployeeWorkDateExport').on("click", function () {
            page.apsWorkShiftModelExport();    
        });
        $('#btnArrangeWorkShift').on("click",function () {
            $('#dg').show();            
            $('#dg').dialog({
                    title: '指定班次',
                    width: 200,
                    height: 120,
                    closed: false,
                    cache: false,
                    modal: true
                });
            });            
    },     
    saveWorkShift:function(newShift,employeename,workdate)
    {
        $.ajax({
            type: "Post",
            url: page.ajaxUrl,            
            data: {action: "saveWorkShift", workshiftId: newShift,employeename:employeename,workdate:workdate},
            cashe: false,
            async: true,
            beforeSend: function () {
            },
            success: function (data) {
                var result = JSON.parse(data);
            if (result.Result) {
                 
                    displayMessage("保存成功", true);
                } else {               
                    displayMessage(result.Message, false);
                }
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
            }
        });
    },        
    searchData:function () { 
        //验证
        var startDate = $("#txtStartDate").datebox('getValue');
        var endDate = $("#txtEndDate").datebox('getValue');
        if ((startDate == "")||(endDate=="")) {
            displayMessage("请选择开始/结束日期", false);
            return;
        }        
        var startDated=Date.parse(startDate);
        var endDated=Date.parse(endDate);
        if(endDate<startDate)
        {
            displayMessage("开始日期不能大于结束日期", false);
            return;
        }     
        //获取汇总
        page.searchApsEmployeeWorkSum();
        //获取明细
        page.searchApsEmployeeWorkDetail();
    },
    searchApsEmployeeWorkDetail: function () {
        var startDate = $("#txtStartDate").datebox('getValue');
        var endDate = $("#txtEndDate").datebox('getValue');
        var gridID = "#gdEmpWkShiftDetailInfo";
        var param = {
            action: "searchApsEmployeeWorkDetail",
            pageSize: page.pageSize,
            pageNumber: page.pageNumber,
            factoryId: $("#selfactory").textbox('getValue'),
            workCenterId: $("#selWorkCenter").textbox('getValue'),
            teamId: $("#selTeam").textbox('getValue'),
            employeeName: $("#txtEmployee").textbox('getValue'),
            fullName: $("#txtFullName").textbox('getValue'),
            startDate: $("#txtStartDate").datebox('getValue'),
            endDate: $("#txtEndDate").datebox('getValue')
        };
        $.ajax({
            type: "Post",
            url: page.ajaxUrl,
            data: param,
            cashe: false,
            async: true,
            beforeSend: function () {
                $(gridID).datagrid('loading');
                $(this).attr("disabled", "disabled"); //禁用按钮
                $.messager.progress({ text: '', msg: '处理中...' });
            },
            success: function (data) {
                //console.log(data);
                $(gridID).datagrid('loaded');
                $(this).removeAttr("disabled"); //恢复按钮
                $.messager.progress('close');
                var result = JSON.parse(data);
                if (result.Result) {
                    //给分页对象赋值
                    page.pagetotal = result.RowCount;
                    $(gridID).datagrid('loadData', { total: result.RowCount, rows: result.DBTable });
                } else {
                    displayMessage(result.Message, false);
                }
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                $(gridID).datagrid('loaded');
                $(this).removeAttr("disabled"); //恢复按钮
                $.messager.progress('close');
                alert(XMLHttpRequest.responseText);                
            }
             
        });
    },
    //查询 汇总 不分页
    searchApsEmployeeWorkSum: function () {
        var startDate = $("#txtStartDate").datebox('getValue');
        var endDate = $("#txtEndDate").datebox('getValue');
        if ((startDate == "")||(endDate=="")) {
            displayMessage("请选择开始/结束日期", false);
            return;
        }
        var columns=[];
        var startDated=Date.parse(startDate);
        var endDated=Date.parse(endDate);
        if(endDate<startDate)
        {
            displayMessage("开始日期不能大于结束日期", false);
            return;
        }

        var date=Math.abs(endDated-startDated);
        var allDay=Math.floor(date/(1000*3600*24));
        for(var i=0;i<=allDay;i++){
            var date=dayjs(startDate).add(i,'day');
            columns.push({ field: date.format('YYYYMMDD'), title: date.format('YYYY-MM-DD'), width: 120 ,align:'center', editor:{
							type:'combobox',
							options:{
								valueField:'WORKSHIFTID',
								textField:'WORKSHIFTNAME',
								data:page.shiftTable
							   }    
                            }});
        }
        page.InitgdEmpWkShiftSumInfo(columns);
        var gridID = "#gdEmpWkShiftSumInfo";
        var param = {
            action: "searchData",
            pageSize: page.pageSize,
            pageNumber: page.pageNumber,
            factoryId: $("#selfactory").textbox('getValue'),
            workCenterId: $("#selWorkCenter").textbox('getValue'),
            teamId: $("#selTeam").textbox('getValue'),
            employeeName: $("#txtEmployee").textbox('getValue'),
            fullName: $("#txtFullName").textbox('getValue'),
            startDate: $("#txtStartDate").datebox('getValue'),
            endDate: $("#txtEndDate").datebox('getValue')
        };
        $.ajax({
            type: "Post",
            url: page.ajaxUrl,
            data: param,
            cashe: false,
            async: true,
            beforeSend: function () {
                $(gridID).datagrid('loading');
                $(this).attr("disabled", "disabled"); //禁用按钮
            },
            success: function (data) {
                //console.log(data);
                $(gridID).datagrid('loaded');
                $(this).removeAttr("disabled"); //恢复按钮
                var result = JSON.parse(data);
                if (result.Result) {
                    //给分页对象赋值
                    page.pagetotal = result.RowCount;
                    $(gridID).datagrid('loadData', { total: result.RowCount, rows: result.DBTable });
                } else {
                    displayMessage(result.Message, false);
                }
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                $(gridID).datagrid('loaded');
                $(this).removeAttr("disabled"); //恢复按钮
                alert(XMLHttpRequest.responseText);
            }
        });
    },
    //分厂下拉初始化
    LoadFactory: function () {
        $.ajax({
            type: "Post",
            url: page.ajaxUrl,
            data: {action: "getFactory"},
            cashe: false,
            async: true,
            beforeSend: function () {
            },
            success: function (data) {
                var result = JSON.parse(data);
                $('#selfactory').combobox({
                    data: result,
                    valueField: 'FACTORYID',
                    textField: 'FACTORYNAME',
                    value: result[0].FACTORYID, //默认值
                    onSelect: function (record) {
                        if (record.FACTORYID !== "") {
                            page.bindWorkCenter(record.FACTORYID); //加载工区
                        }
                    }
                });
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
            }
        });
    },
    //绑定班次
    LoadWorkShift: function () {
        $.ajax({
            type: "Post",
            url: page.ajaxUrl,
            data: {action: "getWorkShift"},
            cashe: false,
            async: true,
            beforeSend: function () {
            },
            success: function (data) {
                var result = JSON.parse(data);
                page.shiftTable=result.DBTable;
                $('#cmbWorkShift').combobox({
                    data: result.DBTable,
                    valueField: 'WORKSHIFTID',
                    textField: 'WORKSHIFTNAME'
                });
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                page.shiftTable=null;
            }
        });
    },    
    //绑定工区
    bindWorkCenter: function (factoryid) {
        $.ajax({
            type: "Post",
            url: page.commonUrl, 
            data: { action:"getWorkcenterByFactory",factoryId: factoryid },
            cashe: false,
            async: true,
            beforeSend: function () {
            },
            success: function (data) {
                var result = JSON.parse(data);
                $('#selWorkCenter').combobox({
                    data: result,
                    valueField: 'WORKCENTERID',
                    textField: 'WORKCENTERNAME',
                    onSelect: function (record) {
                        if (record.WORKCENTERID !== "") {
                            page.bindTeam(record.WORKCENTERID); //加载班组
                        }
                    }
                });
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
            }
        });
    },
    //绑定班组
    bindTeam: function (workcenterid) {
        $.ajax({
            type: "Post",
            url: page.commonUrl,
            data: {action:"getTeamByWorkcenter",workcenterId: workcenterid},            
            cashe: false,
            async: true,
            beforeSend: function () {
            },
            success: function (data) {
                var result = JSON.parse(data);
                $('#selTeam').combobox({
                    data: result,
                    valueField: 'TEAMID',
                    textField: 'TEAMNAME'
                });
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
            }
        });
    },
    //导入组件初始化
    apsUploader: function () {
        var uploader = WebUploader.create({
            // swf文件路径
            swf: page.rootPath + "/Content/webuploader/Uploader.swf",
            // 文件接收服务端。
            server: page.ajaxUrl,
            // 内部根据当前运行是创建，可能是input元素，也可能是flash.
            pick: '#btnEmployeeWorkDateImport',
            // 不压缩image, 默认如果是jpeg，文件上传前会压缩一把再上传！
            resize: false,
            formData: {
                    action: "apsEmployeeWorkDateImport",
                },
            accept: {
                    title: 'Excel',
                    extensions: 'xlsx,xls',
                    mimeTypes: 'excel/*'
                },
        });
        // 当有文件被添加进队列的时候，每次只传一个文件
        uploader.on('fileQueued', function (file) {
            if ($('#txtExcelFileId').val() != "") {
                var f = uploader.getFile($('#txtExcelFileId').val()); //找到上一次队列中的文件
                uploader.removeFile(f, true); //删除掉上一次队列中的文件
            }
            $('#txtExcelFileId').val(file.id);
            clearMessage();
            uploader.upload();
            $.messager.progress({ text: '', msg: '处理中...' });
        });
        //上传成功
        uploader.on('uploadSuccess', function (file, response) {
            clearMessage();
            var result = response;
            displayMessage(result.Message, true);
            $.messager.progress('close');
            if(result.ReturnData!=null){if(result.ReturnData.length>0){page.loadErrorData(result.ReturnData);}}
            var f = uploader.getFile(file.id); //找到上传的文件
            uploader.removeFile(f, true); //将其从队列中的删掉
            $('#txtExcelFileId').val("");

        });
        //上传失败  导入结果，错误行列表
        uploader.on('uploadError', function (file) {
            displayMessage("上传失败", false);
            var f = uploader.getFile(file.id); //找到上传的文件
            uploader.removeFile(f, true); //将其从队列中的删掉
            $.messager.progress('close');
            $('#txtExcelFileId').val("");

        });
    },       
    //排产结果导入，错误行列表
    loadErrorData:function(data){
          $('#ErrorDg').dialog({
            title: '导入错误数据',
            top:50,
            width: '800px',
            height: '400px',
            closed: false,
            cache: false,
            modal: true,
              buttons:[{
				    text:'关闭',
				    handler:function(){$('#ErrorDg').dialog('close');}
			    }]
            });
           $("#ErrorTable").datagrid('loadData',data);
    },  
    //导入模板导出
    apsWorkShiftModelExport: function () {     
        var WorkShiftModel;
        var postData = {
            "action": "apsWorkShiftModelExport",
            "WorkShiftModel": JSON.stringify(WorkShiftModel)
        }
        $.messager.progress({ text: '', msg: '处理中...' });

        var xhr = new XMLHttpRequest();
        //设置响应类型为blob类型
        xhr.responseType = "blob";
        xhr.open("post", page.ajaxUrl, true); 

        /* post 此种传参无效
        xhr.setRequestHeader('Content-Type', 'application/json');
        xhr.send(JSON.stringify(postData));
        */
        // post 这种传参有效
        xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
        xhr.send("action=apsWorkShiftModelExport&WorkShiftModel=" + JSON.stringify(WorkShiftModel));


        xhr.onreadystatechange = function () {
            $.messager.progress('close');
            if (xhr.readyState == 4) {
                if (xhr.status == 200) {
                    if (xhr.getResponseHeader("fileDownload") == "1") {
                        var a = window.document.createElement('a');
                        a.href = window.URL.createObjectURL(new Blob([this.response]));
                        a.download = decodeURI(xhr.getResponseHeader("content-disposition").split('filename=')[1]);
                        document.body.appendChild(a)
                        a.click();
                        document.body.removeChild(a)
                    } else {
                        var reader = new FileReader();
                        reader.readAsText(this.response, 'utf-8');
                        reader.onload = function (e) {
                            var result = JSON.parse(reader.result);
                            displayMessage(result.Message, false);
                        }
                    }

                }
            }
        };
        return;

    },


    //清除方法，重要！！！
    reset: function (iscondition, isresult, isDetail) {
        clearMessage();
        if (iscondition) {
            $('#selfactory').textbox('clear');
            $('#selWorkCenter').textbox('clear');
            $('#selTeam').textbox('clear');

            $('#txtEmployee').textbox('clear');
            $('#txtFullName').textbox('clear');
            $('#txtStartDate').datebox('setValue', dayjs().startOf('month').format('YYYY-MM-DD'));
            $('#txtEndDate').datebox('setValue', dayjs().endOf('month').format('YYYY-MM-DD'));
        }
        if(isresult)
        {
         clearEasyuiDataGrid("gdEmpWkShiftSumInfo", 1); //查询结果列表
         clearEasyuiDataGrid("gdEmpWkShiftDetailInfo", 1); //查询结果列表
        }
                
    }
}
$(function () {
    page.init();
});